package com.cloud.advice;


import com.cloud.advice.domain.response.ResponseResult;
import com.cloud.advice.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 统一返回值处理包装类
 */
public class ResponseBodyWrapperHandler implements HandlerMethodReturnValueHandler {

    private static final Logger _logger = LoggerFactory.getLogger(ResponseBodyWrapperHandler.class);

    private final HandlerMethodReturnValueHandler handler;

    public ResponseBodyWrapperHandler(HandlerMethodReturnValueHandler handler) {
        this.handler = handler;
    }

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return handler.supportsReturnType(returnType);
    }

    @Override
    public void handleReturnValue(Object returnValue,
                                  MethodParameter returnType, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest) throws Exception {
        _logger.info("return data is " + returnValue);
        if (returnValue instanceof Void) {
            returnValue = ResponseUtil.DefaultSuccessResult();
        } else {
            if (!(returnValue instanceof ResponseResult)) {
                returnValue = ResponseUtil.build(200, "success", returnValue);
            }
        }
        handler.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
    }

}